//
// Created by penghuiping on 14/10/25.
// Copyright (c) 2014 joinsoft. All rights reserved.
//

int g_iStartChan = 0;
int g_iPreviewChanNum = 0;
bool g_bDecode = true;

#import "TGDCamera.h"

TGDCamera *g_Camera = NULL;

char *tBuffer;

typedef struct tagHANDLE_STRUCT
{
    int iPreviewID;
    int iPlayPort;
    UIView *pView;
    tagHANDLE_STRUCT()
    {
        iPreviewID = -1;
        iPlayPort = -1;
        pView = NULL;
    }
}HANDLE_STRUCT,*LPHANDLE_STRUCT;

HANDLE_STRUCT g_struHandle[4];


@implementation TGDCamera {
    long userId;
    int previewPort;
    long realPlayID;
    int channel;
    
    UIView                  *m_playView;
    UIView                  *m_multiView[4];
    int                     m_nPreviewPort;
    int                     m_nPlaybackPort;
    FILE					*m_fp;
    
    id                      m_playThreadID;
    unsigned char			*pBuf;
    bool					m_bThreadRun;
    int                     m_lUserID;
    int                     m_lRealPlayID;
    int                     m_lPlaybackID;
    bool                    m_bPreview;
    bool                    m_bRecord;
    bool                    m_bPTZL;
    bool                    m_bVoiceTalk;
}

void g_fExceptionCallBack(DWORD dwType, LONG lUserID, LONG lHandle, void *pUser)
{
    NSLog(@"g_fExceptionCallBack Type[0x%x], UserID[%d], Handle[%d]", dwType, lUserID, lHandle);
}

// preview callback function
void fRealDataCallBack_V40(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer, DWORD dwBufSize, void* pUser)
{
    LPHANDLE_STRUCT pHandle = (LPHANDLE_STRUCT)pUser;
    switch (dwDataType)
    {
        case NET_DVR_SYSHEAD:
            if(pHandle->iPlayPort != -1)
            {
                break;
            }
            if(!PlayM4_GetPort(&pHandle->iPlayPort))
            {
                break;
            }
            if (dwBufSize > 0 )
            {
                if (!PlayM4_SetStreamOpenMode(pHandle->iPlayPort, STREAME_REALTIME))
                {
                    break;
                }
                if (!PlayM4_OpenStream(pHandle->iPlayPort, pBuffer , dwBufSize, 2*1024*1024))
                {
                    break;
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [g_Camera previewPlay:&pHandle->iPlayPort playView:pHandle->pView];
               });
            }
            break;
        default:
            if (dwBufSize > 0 && pHandle->iPlayPort != -1)
            {
//                sleep(0.1);
//                NSLog(@"%f",[[NSDate date] timeIntervalSince1970]);
                ;
               unsigned char *pbuf =(unsigned char*) pBuffer;
                char *t = (char*)malloc(sizeof(Byte)*(dwBufSize+strlen(tBuffer) + 1));    //先分配一块足够的空间
                strcpy(t, tBuffer);   //然后把p复制进去
                strcat(t, pbuf);   //再把a添加到后面
                tBuffer = t;  //最后再赋值给p
                [NSThread sleepForTimeInterval:0.01];
                if(!PlayM4_InputData(pHandle->iPlayPort, (BYTE*)tBuffer, dwBufSize))
                {
                    break;
                }
                
                
            }
            break;
    }
}

-(int) startPreview:(int) iUserID : (int) iStartChan :(UIView *)pView : (int) iIndex
{
    // request stream
    NET_DVR_PREVIEWINFO struPreviewInfo = {0};
    struPreviewInfo.lChannel = iStartChan + iIndex;
    struPreviewInfo.dwStreamType = 1;
    struPreviewInfo.bBlocked = 1;
    g_struHandle[iIndex].pView = pView;
    g_struHandle[iIndex].iPreviewID = NET_DVR_RealPlay_V40(iUserID, &struPreviewInfo, fRealDataCallBack_V40, &g_struHandle[iIndex]);
    if (g_struHandle[iIndex].iPreviewID == -1)
    {
        NSLog(@"NET_DVR_RealPlay_V40 failed:%d",  NET_DVR_GetLastError());
        return -1;
    }
    NSLog(@"NET_DVR_RealPlay_V40 succ");
    
    return g_struHandle[iIndex].iPreviewID;
}

- (void)previewPlay:(int*)iPlayPort playView:(UIView*)playView
{
    m_nPreviewPort = *iPlayPort;
    int iRet = PlayM4_Play(*iPlayPort, (__bridge void *) self.carmeraView);
    PlayM4_PlaySound(*iPlayPort);
    if (iRet != 1)
    {
        NSLog(@"PlayM4_Play fail");
        return;
    }
}

-(void) stopPreview:(int) iIndex
{
    NET_DVR_StopRealPlay(g_struHandle[iIndex].iPreviewID);
    [self  stopPreviewPlay:&g_struHandle[iIndex].iPlayPort];
}

- (void)stopPreviewPlay:(int*)iPlayPort
{
    PlayM4_StopSound();
    if (!PlayM4_Stop(*iPlayPort))
    {
        NSLog(@"PlayM4_Stop failed");
    }
    if(!PlayM4_CloseStream(*iPlayPort))
    {
        NSLog(@"PlayM4_CloseStream failed");
    }
    if (!PlayM4_FreePort(*iPlayPort))
    {
        NSLog(@"PlayM4_FreePort failed");
    }
    *iPlayPort = -1;
}



-(void)cameraController{
    
    BOOL isCon = NET_DVR_PTZControl(realPlayID,
                                    IRIS_OPEN,
                                    0);
    
    NSLog(@"isCon:%zi",isCon);
    
//    BOOL su= NET_DVR_RebootDVR(userId);
//
//    NSLog(@"su:%zi",su);
    
}

-(void)cameraController1{
    
    BOOL isCon = NET_DVR_PTZControl(realPlayID,
                                    IRIS_OPEN,
                                    1);
    
    NSLog(@"isCon:%zi",isCon);
    
    
}

- (instancetype)initWithView:(UIView *)view {
    self = [super init];
    if (self) {
        self.carmeraView = view;
        g_Camera = self;
    }

    return self;
}

+ (instancetype)cameraWithView:(UIView *)view {
    return [[self alloc] initWithView:view];
}

- (void)loginWithIpAddress:(NSString *)ipAddress userName:(NSString *)userName password:(NSString *)password {
       
    BOOL r = NET_DVR_Init();
    NSLog(@"%d", r);
    
    
    NET_DVR_DEVICEINFO_V30 deviceInfo = {0};
    m_lUserID = NET_DVR_Login_V30((char *) [ipAddress UTF8String], 8000,
            (char *) [userName UTF8String], (char *) [password UTF8String],
            &deviceInfo);
    
    if (m_lUserID == -1) {
        UIAlertView *alert = [[UIAlertView alloc]
                initWithTitle:@"错误"
                      message:@"登录失败"
                     delegate:nil
            cancelButtonTitle:@"确定"
            otherButtonTitles:nil];
        [alert show];
    } else {
        NSLog(@"摄像头登录成功");
        //[self play];
        
        if(deviceInfo.byChanNum > 0)
        {
            g_iStartChan = deviceInfo.byStartChan;
            g_iPreviewChanNum = deviceInfo.byChanNum;
        }
        else if(deviceInfo.byIPChanNum > 0)
        {
            g_iStartChan = deviceInfo.byStartDChan;
            g_iPreviewChanNum = deviceInfo.byIPChanNum + deviceInfo.byHighDChanNum * 256;
        }

      m_lRealPlayID =  [self startPreview:m_lUserID :g_iStartChan :_carmeraView :0];
        NSLog(@"error no: %d", NET_DVR_GetLastError());
        if (m_lRealPlayID == -1) {
            UIAlertView *alert = [[UIAlertView alloc]
                    initWithTitle:@"错误"
                          message:@"获取realPlayID失败"
                         delegate:nil
                cancelButtonTitle:@"确定"
                otherButtonTitles:nil];
            [alert show];
        }
        NSLog(@"realPlayID %ld", realPlayID);
    }
}



-(void) stop{
    [self stopPreview:0];
//    if (m_lRealPlayID != -1)
//    {
//        NET_DVR_StopRealPlay(m_lRealPlayID);
//        m_lRealPlayID = -1;
//    }
//    
//    if(m_nPreviewPort >= 0)
//    {
//        if(!PlayM4_StopSound())
//        {
//            NSLog(@"PlayM4_StopSound failed");
//        }
//        if (!PlayM4_Stop(m_nPreviewPort))
//        {
//            NSLog(@"PlayM4_Stop failed");
//        }
//        if(!PlayM4_CloseStream(m_nPreviewPort))
//        {
//            NSLog(@"PlayM4_CloseStream failed");
//        }
//        if (!PlayM4_FreePort(m_nPreviewPort))
//        {
//            NSLog(@"PlayM4_FreePort failed");
//        }
//        m_nPreviewPort = -1;
//    }
    [self logout];

}

- (void)dealloc {
    [self logout];
    
    
    self.carmeraView = nil;
}

- (void)logout {
    if(m_lUserID>-1){
        
        NSLog(@"logout");
       
        NET_DVR_Logout(m_lUserID);
        
        NET_DVR_Cleanup();
        userId=-1;
    }
}

@end